﻿using System.Windows;
using System.Windows.Data;

namespace MaxStoreShop.Core
{
    public static class WindowValidator
    {
        public static bool IsValid(DependencyObject parent)
        {
            // Validate all the bindings on the parent
            var valid = true;
            var localValues = parent.GetLocalValueEnumerator();
            while (localValues.MoveNext())
            {
                var entry = localValues.Current;
                if (!BindingOperations.IsDataBound(parent, entry.Property)) 
                    continue;

                var binding = BindingOperations.GetBinding(parent, entry.Property);
                if (binding.ValidationRules.Count <= 0) 
                    continue;

                var expression = BindingOperations.GetBindingExpression(parent, entry.Property);
                expression.UpdateSource();

                if (expression.HasError)
                {
                    valid = false;
                }
            }

            // Validate all the bindings on the children
            var children = LogicalTreeHelper.GetChildren(parent);
            foreach (object obj in children)
            {
                if (obj is DependencyObject)
                {
                    DependencyObject child = (DependencyObject)obj;
                    if (!IsValid(child)) { valid = false; }
                }
            }
            return valid;
        }
    }
}
